package com.example.config;

import com.example.constant.CrowdConstant;
import com.example.entity.po.MemberPO;
import com.example.entity.po.Role;
import com.example.service.MemberProviderHandler;
import com.example.service.api.AuthService;
import com.example.service.api.RoleService;
import com.example.util.ResultEntity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.*;

@Component
public class CrowdUserDetailsService implements UserDetailsService {
    @Autowired
    private MemberProviderHandler memberProviderHandler;

//    @Autowired
//    private AdminService adminService;
//
    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        // 通过用户名得到Admin对象
//        Admin admin = adminService.getAdminByLoginAcct(username);
//
        ResultEntity<MemberPO> resultEntity = memberProviderHandler.getMemberPOByLoginAcctRemote(username);



        // 查询操作成功，则取出MemberPO对象
        MemberPO memberPO = resultEntity.getData();
        // 通过AdminId得到角色List

        List<Role> roles =   roleService.queryAssignedRoleList(memberPO.getId());
//
//        // 通过AdminId得到权限name地List
        List<String> authNameList = authService.getAuthNameByAdminId(memberPO.getId());
//
        // 创建List用来存放GrantedAuthority（权限信息）
        List<GrantedAuthority> authorities = new ArrayList<>();

        // 远程方法调用，通过loinAcct，得到数据库中的对应Member
        //ResultEntity<MemberPO> resultEntity = mySQLRemoteService.getMemberPOByLoginAcctRemote(username);

        // 向List存放角色信息，注意角色必须要手动加上 “ROLE_” 前缀

            //String roleName = "ROLE_" + "role.getName()";
        for (Role role : roles) {
            String roleName = "ROLE_" + role.getName();
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);
            authorities.add(simpleGrantedAuthority);
        }


        // 向List存放权限信息
        for (String authName : authNameList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);
            authorities.add(simpleGrantedAuthority);
        }

        // 将Admin对象、权限信息封装入SecurityAdmin对象（User的子类）
        SecurityMemberPO securityAdmin = new SecurityMemberPO(memberPO, authorities);
        //session.setAttribute
        // 返回SecurityAdmin对象
        return securityAdmin;
    }
}
